# import necessary packages
import cv2 as cv
import argparse

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="The path to the image")
args = vars(ap.parse_args())

# load the image and convert it to grascale
image = cv.imread(args["image"])
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cv.imshow("Original", image)

# apply a series of erosions
for i in range(0, 3):
    eroded = cv.erode(gray.copy(), None, iterations=i + 1)
    cv.imshow("Eroded {} times".format(i + 1), eroded)
    cv.waitKey(0)

# close all windows to cleanup the screen
cv.destroyAllWindows()
cv.imshow("Original", image)

# apply a series of dilations
for i in range(0, 3):
    dilated = cv.dilate(gray.copy(), None, iterations=i + 1)
    cv.imshow("Dilated {} times".format(i + 1), dilated)
    cv.waitKey(0)

# close all windows to cleanup the screen an initialize the list
# of kernels sizes that will be applied to the image
cv.destroyAllWindows()
cv.imshow("Original", image)
kernelSizes = [(3, 3), (5, 5), (7, 7)]

# loop over kernels and apply an "opening" operation to the image
for kernelSize in kernelSizes:
    kernel = cv.getStructuringElement(cv.MORPH_RECT, kernelSize)
    opening = cv.morphologyEx(gray, cv.MORPH_OPEN, kernel)
    cv.imshow("Opening: ({},{})".format(kernelSize[0], kernelSize[1]), opening)
    cv.waitKey(0)

# close all windows to cleanup the screen
cv.destroyAllWindows()
cv.imshow("Original",image)

# loop over the kernels and apply a "closing" operation to the image
for kernelSize in kernelSizes:
    kernel = cv.getStructuringElement(cv.MORPH_RECT,kernelSize)
    closing = cv.morphologyEx(gray,cv.MORPH_CLOSE,kernel)
    cv.imshow("Closing: ({},{})".format(kernelSize[0],kernelSize[1]),closing)
    cv.waitKey(0)

# close all windows to cleanup the screen
cv.destroyAllWindows()
cv.imshow("Original",image)

# loop over the kernels and apply a "morphological gradient" operation
# to the image
for kernelSize in kernelSizes:
    kernel = cv.getStructuringElement(cv.MORPH_RECT,kernelSize)
    gradient = cv.morphologyEx(gray,cv.MORPH_GRADIENT,kernel)
    cv.imshow("Gradient: ({},{})".format(kernelSize[0],kernelSize[1]),gradient)
    cv.waitKey(0)